package com.starry.androidmvvmexample.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

/**
 *
 * @author lixu157
 * @date 2025/5/2
 * @des 描述信息
 */
abstract class BaseVMActivity<VB : ViewDataBinding, VM : ViewModel>(
    private val viewModelClass: Class<VM>,
    private val inflater: (LayoutInflater) -> VB
) : BaseActivity(

) {

    /**
     * viewDataBinding
     */
    protected lateinit var mBinding: VB

    /**
     * 通过反射拿到ViewModel并且注册
     */
    protected val mViewModel: VM by lazy {
        ViewModelProvider(this)[viewModelClass]
    }

    protected var viewModelId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initParams()//初始化页面接受的参数
        initViewDataBinding()
        initView()
        initViewObservable()
        initData()
        requestData()
    }

    private fun initViewDataBinding() {
        mBinding = inflater(layoutInflater)
        viewModelId = initVariableId()
        //关联ViewModel
        mBinding.setVariable(viewModelId, mViewModel)
        //支持LiveData绑定xml，数据改变，UI自动会更新
        mBinding.setLifecycleOwner(this)
        setContentView(mBinding.root)
    }

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    abstract fun initVariableId(): Int

    override fun initParams() {
        //空方法，子类可选择实现
    }

    override fun initData() {
        //空方法，子类可选择实现
    }

    override fun requestData() {
        //空方法，子类可选择实现
    }

}